今天來學習 Jest 測試的 Group 寫法:
情境:如果我的測試檔案中,有多個測試函式。我想要把相關連的測試群組起來,方便執行測試時一起執行。
原本的寫法:
// Button
test("Render a Log In Button", () => {
render(<LogInButton />);
const textEl = screen.getByText("Log In");
expect(textEl).toBeInTheDocument();
});
// Button
test("Render a Log Out Button", () => {
render(<LogInButton />);
const textEl = screen.getByText("Log Out");
expect(textEl).toBeInTheDocument();
});
// Greet
test("Render a Greet Component", () => {
render(<Greet name="Joanna" />);
const textEl = screen.getByText("Hello");
expect(textEl).toBeInTheDocument();
});
分組寫法:加入關鍵字 describe
// Button
describe("Button", () => {
test("Render a Log In Button", () => {
render(<LogInButton />);
const textEl = screen.getByText("Log In");
expect(textEl).toBeInTheDocument();
});
test("Render a Log Out Button", () => {
render(<LogInButton />);
const textEl = screen.getByText("Log Out");
expect(textEl).toBeInTheDocument();
});
});
// Greet
test("Render a Greet Component", () => {
render(<Greet name="Joanna" />);
const textEl = screen.getByText("Hello");
expect(textEl).toBeInTheDocument();
});
describe()
也有提供describe.only()
describe.skip()
的寫法,方便群組測試執行。